package com.cssy.xxkj.logic.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.byd.acegiext.domain.User;
import com.cssy.xxkj.logic.contants.BillStatusUtil;
import com.cssy.xxkj.logic.contants.BillTypeConstant;
import com.cssy.xxkj.logic.dao.LogicOutsideStockDAO;
import com.cssy.xxkj.logic.dao.LogicOutsideStockItemDAO;
import com.cssy.xxkj.logic.entity.LogicOutsideStockDO;
import com.cssy.xxkj.logic.entity.LogicOutsideStockItemDO;
import com.cssy.xxkj.logic.service.ILogicHsUtilService;
import com.cssy.xxkj.logic.service.ILogicOutsideStockService;
import com.plat.exception.SyBaseException;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.DateUtils;
import com.plat.util.GlobalResLoader;
import com.plat.util.IDCodeTypeUtil;
import com.plat.util.SessionUtil;
import com.yuendong.sy.po.code.SyCode;
import com.yuendong.sy.service.code.impl.SyCodeService;

@Service("logicOutsideStockService")
public class LogicOutSideStockServiceImpl implements ILogicOutsideStockService {
	
	@Resource(name = "logicOutsideStockDAO")
	private LogicOutsideStockDAO logicOutsideStockDAO;
	
	@Resource(name = "logicOutsideStockItemDAO")
	private LogicOutsideStockItemDAO logicOutsideStockItemDAO;
	
	@Resource(name = "logicHsUtilService")
	private ILogicHsUtilService logicHsUtilService;
	
	@Resource(name = "syCodeService")
	private SyCodeService syCodeService;

	@Override
	public SearchResult findListByExample(SearchConditions scs)
			throws SyBaseException {
		SearchResult rs=new SearchResult(scs);
		List<LogicOutsideStockDO>  list = logicOutsideStockDAO.find(scs);
		rs.setRecordCount(logicOutsideStockDAO.count(scs));
		rs.setResults(list);
		return rs;
	}
	
	@Override
	public List<LogicOutsideStockItemDO> findItemListByMap(Map<String, Object> paramMap)
		throws SyBaseException{
		return logicOutsideStockItemDAO.findListByMap(paramMap);
	}

	@Override
	public Integer delete(String id, User user) throws SyBaseException {
		return logicOutsideStockDAO.deleteLogicOutsideStockDOByPrimaryKey(id);
	}

	@Override
	public Integer update(LogicOutsideStockDO outSideIn, User user)
			throws SyBaseException {
		outSideIn.setBizModifyName(user.getName());
		outSideIn.setBizModifyDate(new Date());
		outSideIn.setBizVersionMark(outSideIn.getBizVersion());
		outSideIn.setBizVersion(outSideIn.getBizVersion()+1);
		return logicOutsideStockDAO.updateLogicOutsideStockDO(outSideIn);
	}

	@Override
	public LogicOutsideStockDO save(LogicOutsideStockDO outSideIn, User user)
			throws SyBaseException {
		outSideIn.setBizVersion(Integer.valueOf(1));
		outSideIn.setBizCreatorDate(new Date());
		outSideIn.setBizCreatorName(user.getName());
		logicOutsideStockDAO.insertLogicOutsideStockDO(outSideIn);
		return outSideIn;
	}
	
	@Override
	public void outSideInSave(LogicOutsideStockDO curAP, HttpServletRequest request)
		throws SyBaseException{
		String dataitem = request.getParameter("dataitem");
		String detadele = request.getParameter("datadele");
		String zd006Date = request.getParameter("zd006Date");
		String submitFlag = request.getParameter("submitFlag");
		//标识是外联入库或者是委外后入库
		String zdType = request.getParameter("zdType");
		if(StringUtils.isNotBlank(zd006Date)){
			curAP.setZd006Date(DateUtils.stringToDate(zd006Date));
		}else{
			curAP.setZd006Date(new Date());
		}
		try{
			if(BillStatusUtil.OUTSIDEIN_STATUS_THREE.equals(submitFlag)){
				//驳回
				LogicOutsideStockDO outSide = logicOutsideStockDAO.findLogicOutsideStockDOByPrimaryKey(curAP.getId());
				if(outSide==null){
					throw new SyBaseException("数据发生改变，请重新提交。");
				}
				curAP.setZd001Status(submitFlag);
				this.update(outSide, SessionUtil.getUser(request));
			}else{
				String zd001Id = "";
				String zd001Code = "";
				curAP.setZd001Status(submitFlag);
				if(curAP==null || StringUtils.isBlank(curAP.getId())){
					//新增
					zd001Id = IDCodeTypeUtil.getId();
					curAP.setId(zd001Id);
					if("exter".equals(zdType)){
						zd001Code = syCodeService.getCode(BillTypeConstant.OUTSIDEIN,BillTypeConstant.OUTSIDEIN,SyCode.DATE_YYMM,5);
					}
					if("inter".equals(zdType)){
						zd001Code = syCodeService.getCode(BillTypeConstant.OUTSIDEINWH,BillTypeConstant.OUTSIDEINWH,SyCode.DATE_YYMM,5);
					}
					curAP.setZd001Code(zd001Code);
					this.save(curAP, SessionUtil.getUser(request));
				}else{
					//修改
					zd001Id = curAP.getId();
					zd001Code = curAP.getZd001Code();
					Integer rowUp = this.update(curAP, SessionUtil.getUser(request));
					if(rowUp==null||rowUp.intValue()==0){
						throw new SyBaseException("数据发生改变，请重新提交。");
					}else{
						if(StringUtils.isNotBlank(detadele)){
							List<LogicOutsideStockItemDO> outSideItemList = JSONArray.parseArray(detadele,LogicOutsideStockItemDO.class);
							for(LogicOutsideStockItemDO outSideItem : outSideItemList){
								if(outSideItem==null||StringUtils.isBlank(outSideItem.getId())){
									continue;
								}
								logicOutsideStockItemDAO.deleteLogicOutsideStockItemDOByPrimaryKey(outSideItem.getId());
							}
						}
					}
				}
				
				//新增
				List<LogicOutsideStockItemDO> outItemList = JSONArray.parseArray(dataitem,LogicOutsideStockItemDO.class);
				Map<String,Object> paramMap = new HashMap<String,Object>();
				paramMap.put("zd001Id",zd001Id);
				paramMap.put("zd001Code",zd001Code);
				if(BillStatusUtil.OUTSIDEIN_STATUS_FOUR.equals(submitFlag)){
					//需要修改库存
					paramMap.put("user", SessionUtil.getUser(request));
					this.outSideInSaveOrUpdateOrStock(outItemList, paramMap, true);
				}else{
					//不需要修改库存
					this.outSideInSaveOrUpdateOrStock(outItemList, paramMap, false);
				}
			}
		}catch(Exception e){
			e.printStackTrace();
			
		}
	}
	/**
	 * 新增/修改委外入库item，同时是否修改库存
	 * @param outItemList
	 * @param paramMap
	 * @param upStock
	 * @throws SyBaseException
	 */
	private void outSideInSaveOrUpdateOrStock(List<LogicOutsideStockItemDO> outItemList, Map<String,Object> paramMap,boolean upStock)
			throws SyBaseException{
		try{
			LogicOutsideStockDO outSide = logicOutsideStockDAO.findLogicOutsideStockDOByPrimaryKey(paramMap.get("zd001Id")+"");
			for(LogicOutsideStockItemDO outItem : outItemList){
				if(outItem==null){
					continue;
				}
				if(StringUtils.isBlank(outItem.getId())){
					//新增item
					outItem.setId(IDCodeTypeUtil.getId());
					outItem.setZd001SideInId(paramMap.get("zd001Id")+"");
					outItem.setZd001SideInCode(paramMap.get("zd001Code")+"");
					this.logicOutsideStockItemDAO.insertLogicOutsideStockItemDO(outItem);
					if(upStock){
						//修改库存
						User user = (User)paramMap.get("user");
						this.logicHsUtilService.processHsOutSideInItem(outSide, outItem, user);
					}
				}else{
					//修改item
					this.logicOutsideStockItemDAO.updateLogicOutsideStockItemDO(outItem);
					if(upStock){
						//修改库存
						User user = (User)paramMap.get("user");
						this.logicHsUtilService.processHsOutSideInItem(outSide, outItem, user);
					}
				}
			}
		}catch(Exception e){
			e.printStackTrace();
			throw new SyBaseException(GlobalResLoader.getOpfailed()+ e.getMessage());
		}
	}

	@Override
	public LogicOutsideStockDO findListById(String id) throws SyBaseException {
		return logicOutsideStockDAO.findLogicOutsideStockDOByPrimaryKey(id);
	}

	@Override
	public Integer deleteBizRemoved(String id) throws SyBaseException {
		return this.logicOutsideStockDAO.deleteBizRemoved(id);
	}

}
